package com.excel;

import com.excel.data.CheckExcelRowDTO;
import com.google.common.collect.Lists;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * @author yutao
 * @since 2020/4/30 3:21 下午
 */
public class ExcelTest {

    public static void main(String[] args) throws ReflectiveOperationException {

        ExcelStockCheckService excelStockCheckService = new ExcelStockCheckService();
        excelStockCheckService.setStockUnitType(10);

        // 为了获取门诊名称
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("盘点列表");
        String[] top = new String[]{"1", "否", "药品", "10"};

        List<CheckExcelRowDTO> stoCheckExcelRowDTOS = Lists.newArrayList();

        // 添加顶级表头 门诊ID和是否是诊室
        excelStockCheckService.download(stoCheckExcelRowDTOS, sheet, top);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String format = dateTimeFormatter.format(now);
        String fileName = "门诊盘点单";
        fileName += format + ".xlsx";
        writeWorkbookToFile(fileName, workbook);

    }


    /*------------------------------------ 文件操作 ------------------------------------*/

    protected static void writeWorkbookToFile(String filename, Workbook workbook) {

        Connector connector = new Connector();
        Request request = new Request(connector);
        Response response = new Response();

        // springboot 项目中本来是：
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        try (OutputStream os = response.getOutputStream()) {
            //转码之后下载的文件不会出现中文乱码
            filename = new String(filename.getBytes("gbk"), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType(request.getServletContext().getMimeType(filename));
            workbook.write(os);
            os.flush();
        } catch (IOException error) {
            throw new ServerErrorException("文件生成失败", error);
        }
    }


    /**
     * 上传盘点
     * @return
     */
    /*public boolean updateMedicineStock(@RequestParam("file") MultipartFile file) throws IOException {
        ExcelStockCheckService excelStockCheckService = new ExcelStockCheckService();
        StockChecker stockChecker = new StockChecker();

        if (file == null || file.isEmpty()) {
            throw new ApiException(WMS_STOCK_CHECK_FILE_EMPTY);
        }
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (!"xlsx".equals(extension)) {
            throw new ApiException(WMS_STOCK_CHECK_FILE_FORMAT_ERROR);
        }
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        // 校验指定字段的数据格式，并解析文件数据
        List<CheckExcelRowDTO> checkExcelRowDTOS = excelStockCheckService.uploadTipError(workbook, false);
        Optional.of(checkExcelRowDTOS).filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ApiException(WMS_NOT_EXISTED_CHECK_FILE));
        boolean isFormatError, isDataError = false;
        isFormatError = excelStockCheckService.checkErrorAndWriteWorkbook(workbook, checkExcelRowDTOS);
        if (!isFormatError) {
            // 没有错误，则校验Excel数据
            stockChecker.checkExcelData(checkExcelRowDTOS);
            isDataError = excelStockCheckService.checkErrorAndWriteWorkbook(workbook, checkExcelRowDTOS);
        }
        if (isDataError || isFormatError) {
            String fileName = "盘点导入报错提示"
                    + System.currentTimeMillis()
                    + "." + "xlsx";
            writeWorkbookToFile(fileName, workbook);
            throw new ApiException(WMS_NOT_EXISTED_CHECK_FILE);
        }
        // 开始盘点
//        stockCheckFacade.saveExcelCheck(checkExcelRowDTOS, getUser().getName());  业务操作
        return true;
    }*/

}
